package org.example.handler;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.utils.SocketMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.DataInput;
import java.time.LocalDateTime;

@Component
public class WebSocketHandler extends AbstractWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        WsSessionManager.add(session.getId(),session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 获得客户端传来的消息
        String payload = message.getPayload();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            SocketMessage socketMessage = objectMapper.readValue(payload, SocketMessage.class);
            String[] types = socketMessage.getLog().getDes();
            String uname = socketMessage.getLog().getUname();

        }catch (Exception e){
            System.err.println(e);;
        }
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        WsSessionManager.removeAndClose(session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

        WsSessionManager.removeAndClose(session.getId());
    }
}
